package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod hm = (HandlerMethod) handler;


        System.out.println(handler);
        System.out.println(handler.getClass());
        // 拦截不登录的所有请求,如果请求中没有带 token 或者 根据 token 在 redis 中查不到,则拦截
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserInfoByToken(token);
        // 如果从 user 对象为空,则提示 "前先登录"
        if (user==null){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
            return false;
        }
        return true;
    }
}
